package com.yuhanginfo.modules.web.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yuhanginfo.common.service.WebCrudService;
import com.yuhanginfo.modules.web.dao.CustomerHistoryViewDao;
import com.yuhanginfo.modules.web.dao.GoodsListDao;
import com.yuhanginfo.modules.web.entity.CustomerHistoryView;
import com.yuhanginfo.modules.web.entity.WebGoods;

@Service
@Transactional(readOnly = true)
public class CustomerHistoryViewService extends WebCrudService<CustomerHistoryViewDao, CustomerHistoryView> {
	
	@Autowired
	private CustomerHistoryViewDao dao;
	@Autowired
	private GoodsListDao goodsListDao;
	
	@Transactional(readOnly = false)
	public List<WebGoods> getHistoryGoodsByIp(String ip){
		Map<String, String> params=new HashMap<String, String>();
		params.put("useIp", ip);
		List<CustomerHistoryView> hisList=dao.getHistoryGoodsByIp(params);
		List<WebGoods> webGoodsList=new ArrayList<WebGoods>();
		for(CustomerHistoryView c:hisList) {
			Map<String, String> goodsParams=new HashMap<String, String>();
			goodsParams.put("goodsCode", c.getGoodsCode());
			goodsParams.put("storeCode", c.getStoreCode());
			goodsParams.put("useIp", ip);
			WebGoods webGoods=goodsListDao.getGoodsByCode(goodsParams);
			//如果对象不存在，则删除
			if(webGoods!=null) {
				webGoodsList.add(webGoods);
			}else {
				delete(goodsParams);
			}
		}
		return webGoodsList;
	}
	
	public Integer getNum(Map<String, String> params) {
		return dao.getNum(params);
	}
	
	public Integer getNumByIp(Map<String, String> params) {
		return dao.getNumByIp(params);
	}
	
	
	@Transactional(readOnly = false)
	public void save(String goodsCode,String storeCode,String useIp) {
		Map<String, String> params=new HashMap<String, String>();
		params.put("goodsCode", goodsCode);
		params.put("storeCode", storeCode);
		params.put("useIp", useIp);
		if(getNum(params)>0) {
			delete(params);
		}
		if(getNumByIp(params)>=4) {
			dao.deleteLast(params);
		}
		CustomerHistoryView customerHistoryView=new CustomerHistoryView();
		customerHistoryView.setGoodsCode(goodsCode);
		customerHistoryView.setStoreCode(storeCode);
		customerHistoryView.setUseIp(useIp);
		super.save(customerHistoryView);
	}
	
	@Transactional(readOnly = false)
	public void delete(Map<String, String> params) {
		dao.delete(params);
	}
	
	@Transactional(readOnly = false)
	public void deleteRub() {
		dao.deleteRub();
	}
	
}
